package com.grj.template.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.grj.template.boot.domain.R;
import com.grj.template.boot.domain.User;
import com.grj.template.boot.service.UserService;
import com.grj.template.boot.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("register")
@Api(tags = "注册管理")
@RequiredArgsConstructor
public class RegisterController {

    private final UserService userService;

    private final PasswordEncoder passwordEncoder;

    @PostMapping
    @ApiOperation(value = "用户注册", notes = "根据User对象创建新用户")
    public R<String> register(@RequestBody User user) throws Exception {

        if(userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername())) != null){
            throw new Exception("用户已存在:"+this.getClass().getName());

        }
        String password = passwordEncoder.encode(user.getPassword());
        user.setPassword(password);
        boolean save = userService.save(user);
        if (!save){
            throw new Exception("用户注册失败:"+this.getClass().getName());
        }
        return R.okMsg("注册成功");
    }
}
